# -*- coding: utf-8 -*-
#coding=utf-8

import web
import os
import config
from action.admin.base import adminAction
from model.image import image
from model.album import album
from model.user import user

'''
Admin controller: producing image administration views.
'''
class refererAction(adminAction):
    def __init__(self, name = '图片管理'):
        adminAction.__init__(self, name)


    def GET(self, name):
        if name == 'list':
            return self.list()
        elif name == 'delete':
            return self.delete()
        elif name == 'listForBatchDel':
            return self.listForBatchDel()
        elif name == 'add':
            return self.add()
        elif name == 'edit':
            return self.edit()
        elif name == 'thumbnail':
            return self.thumbnail()
        else:
            return self.notFound()

    def POST(self, name):
        if name == 'save':
            return self.save()
        elif name == 'deleteBatch':
            return self.deleteBatch()
        else:
            return self.notFound()

    def list(self):
        inputParams = self.getInput()
        page = int(inputParams['page']) if inputParams.has_key('page') else 1
        count = config.COUNT_PER_PAGE
        offset= (page-1)*count if page > 0 else 0
   
        condition = {}
        imgObj = image()
        listData = imgObj.getOne('COUNT(*) AS `total`', condition)
        totalCount = listData['total']
        imgList = imgObj.getList('*', condition, 'id desc', str(offset) + ',' + str(count))
        
        pageString = self.getPageStr(self.makeUrl('/admin/image/list'), page, count, totalCount)
        self.privData['IMAGE_LIST'] = imgList
        self.privData['PAGE_STRING'] = pageString
        self.privData['ALBUM_LIST'] = {}

        condition = {}
        albumList = album().getList('*', condition)
        self.privData['ALBUM_LIST'] = {}
        for item in albumList:
            self.privData['ALBUM_LIST'][item['id']] = item['name']

        return self.display('imageList')

    def listForBatchDel(self):
        inputParams = self.getInput()
        page = int(inputParams['page']) if inputParams.has_key('page') else 1
        count = config.COUNT_PER_PAGE
        offset= (page-1)*count if page > 0 else 0
        condition = {}
        imgObj = image()
        listData = imgObj.getOne('COUNT(*) AS `total`', condition)
        totalCount = listData['total']
        imgList = imgObj.getList('*', condition, 'id desc', str(offset) + ',' + str(count))
        
        pageString = self.getPageStr(self.makeUrl('/admin/image/list'), page, count, totalCount)
        self.privData['IMAGE_LIST'] = imgList
        self.privData['PAGE_STRING'] = pageString
        self.privData['ALBUM_LIST'] = {}

        condition = {}
        albumList = album().getList('*', condition)
        self.privData['ALBUM_LIST'] = {}
        for item in albumList:
            self.privData['ALBUM_LIST'][item['id']] = item['name']

        return self.display('imageBatchDel')

    def add(self):
        condition = {}
        albumList = album().getList('*', condition)

        self.privData['ALBUM_LIST'] = {}
        for item in albumList:
            self.privData['ALBUM_LIST'][item['id']] = item['name']

        userList = user().getList('*', condition)
        self.privData['USER_LIST'] = {}
        for item in userList:
            self.privData['USER_LIST'][item['id']] = item['nickname']

        return self.display('imageAdd')

    def delete(self):
        inputParams = self.getInput()

        condition = {'id': int(inputParams['id'])}
        img = image().getOne('*', condition)
        if not img:
            return self.error(msg='对象不存在', url=self.makeUrl('/admin/image/list'))

        try:
            image().delete(condition)

            from uploadmgr import httpFileSystem as fs 
            os.unlink(fs().imageURIFromUUID(img['uuid']))
        except Exception, e:
            return self.error(msg='对象删除失败: %s' % e, url=self.makeUrl('/admin/image/list'))
        
        return self.success(msg='对象删除成功', url=self.makeUrl('/admin/image/list'))

    def deleteBatch(self):
        inputParams = self.getInput()
        idList = inputParams['delitems'].split(",")
        if (len(idList)==1):
            return self.error(msg='不能删除系统默认缩略图', url=self.makeUrl('/admin/image/list'))
        elif(len(idList)>1):
            idList.remove('1')
        try:
            condition = ' id IN (' + ','.join(idList) +')'
            image().delete(condition)
        except Exception, e:
            return self.error(msg='对象删除失败: %s' % e, url=self.makeUrl('/admin/image/list'))

        return self.success(msg='对象删除成功', url=self.makeUrl('/admin/image/list'))


    def save(self):
        userInput= self.getInput()

        data = {
            'desc':     self.htmlunquote(userInput['desc']),
            'status':   int(userInput['status']),
            'album':    int(userInput['album']),
            'ref':      userInput['ref'],
            'owner':    userInput['owner'],
        }      

        try:
            condition = {'id': int(userInput['id'])}
            image().update(data, condition)
        except Exception, e:
            return self.error(msg='对象更新失败: %s' % e, url=self.makeUrl('/admin/image/list'))

        return self.success(msg='对象更新成功', url=self.makeUrl('/admin/image/list'))

    def edit(self):
        inputParams = self.getInput()

        condition={'id': int(inputParams['id'])}
        img = image().getOne('*', condition)
        if not img:
            return self.error(msg='对象不存在', url=self.makeUrl('/admin/image/list'))

        self.privData['IMAGE_INFO'] = img

        condition = {}
        albumList = album().getList('*', condition)
        self.privData['ALBUM_LIST'] = {}
        for item in albumList:
            self.privData['ALBUM_LIST'][item['id']] = item['name']

        userList = user().getList('*', condition)
        self.privData['USER_LIST'] = {}
        for item in userList:
            self.privData['USER_LIST'][item['id']] = item['nickname']

        return self.display('imageEdit')

    def thumbnail(self):
        inputParams = self.getInput()

        try:
            condition={'id': int(inputParams['id'])}
            img = image().getOne('*', condition)

            import base64
            return base64.b64decode(img['thumbnail'])
        except Exception, e:
            from imaging import imaging
            return imaging.defaultThumbnail()


